package com.fortune.controller;

import com.fortune.base.BaseController;
import com.fortune.constants.RoleConstants;
import com.fortune.dto.excution.SalesManExcution;
import com.fortune.dto.excution.SmsExcution;
import com.fortune.dto.in.salesMan.*;
import com.fortune.entity.PhoneAndPassword;
import com.fortune.entity.UserIdAndName;
import com.fortune.enums.SalesManEnum;
import com.fortune.enums.SmsEnum;
import com.fortune.service.DriverService;
import com.fortune.service.SalesManService;
import com.fortune.service.SmsService;
import com.fortune.util.TokenUtil;
import com.fortune.vo.salesMan.SalesManData;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fortune.base.BaseAPIExcution;
import com.fortune.common.redis.RedisClient;
import com.fortune.constants.redis.CacheKeys;
import com.fortune.vo.salesMan.LoginSalesManInfo;
import com.fortune.vo.salesMan.SalesManInfo;

@Api(value = "wechat/salesMan", description = "业务员账号相关", tags = {"微信小程序（业务员）：登录"})
@RestController
@RequestMapping("wechat/salesMan")
public class SalesManController extends BaseController{
	@Autowired
	private RedisClient redisClient;

	@Autowired
	private SalesManService salesManService;

	@Autowired
	private DriverService driverService;
	
	@ApiOperation(value = "业务员登录", nickname = "salesManLogin", notes = "", tags={ "@郭阳" })
    @PostMapping(value = "login",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<LoginSalesManInfo> login(@Validated @RequestBody SalesManLoginDto salesManLoginDto) {
		String phone = salesManLoginDto.getPhone();
		String password = salesManLoginDto.getPassword();
		String findPostByPhone = driverService.findPostByPhone(phone);
		//验证手机号是否存在  PhoneAndPassword这里有厂商和经销商id
		PhoneAndPassword finPhoneIsExist = salesManService.finPhoneIsExist(phone);
		if(finPhoneIsExist == null){
			return new SalesManExcution<LoginSalesManInfo>(null, SalesManEnum.ACCOUNT_IS_NOT_EXIST);
		}
		if(!findPostByPhone.equals(RoleConstants.SALSEMAN_ID)){
			return new SalesManExcution<LoginSalesManInfo>(null, SalesManEnum.SALESMAN_LOGIN_ERROR);
		}
		//验证密码是否正确
		String passwords = finPhoneIsExist.getPassword();
		if(!password.equals(passwords)){
			return new SalesManExcution<LoginSalesManInfo>(null, SalesManEnum.PASSWORD_ERROR);
		}
		//验证账号是否被禁用
		String status = finPhoneIsExist.getStatus();
		if(status.equals("NO")){
			return new SalesManExcution<LoginSalesManInfo>(null, SalesManEnum.ACCOUNT_IS_DISABLED);
		}
		String did = finPhoneIsExist.getDid();
		String id = finPhoneIsExist.getId();
		//获取随机唯一字符串
		String token = TokenUtil.genToken();
		String loginToken = id + "," + did + "," + phone;
		//key CacheKeys+随机字符串 value 手机号 存到redis里
		redisClient.save(loginToken, 60*24, CacheKeys.SALES_MAN_LOGIN_TOKEN, token);
		LoginSalesManInfo findLoginSalesManInfo = salesManService.findLoginSalesManInfo(phone);
		findLoginSalesManInfo.setToken(token);
		return new SalesManExcution<LoginSalesManInfo>(findLoginSalesManInfo, SalesManEnum.LOGIN_SUCCESS);
	}

	@ApiOperation(value = "业务员验证手机号", nickname = "salesManVeriPassword", notes = "", tags={ "@郭阳" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@PostMapping(value = "password/veri",
			produces = { MediaType.APPLICATION_JSON_VALUE },
			consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> veriPassword(@Validated @RequestBody SalesManVeriPasswordDto salesManVeriPasswordDto) {
		String phone = salesManVeriPasswordDto.getPhone();
		String code = salesManVeriPasswordDto.getCode();
		String codes = redisClient.get(CacheKeys.EMAIL_SEND_WECHAT_CODE,phone);
		if (!code.equals(codes)){
			return new SalesManExcution<Void>(null, SalesManEnum.VERIFICATION_ERROR);
		}
		return new SalesManExcution<Void>(null, SalesManEnum.VERIFICATION_SUCCESS);
	}

	@ApiOperation(value = "业务员重置密码", nickname = "salesManResetPassword", notes = "", tags={ "@郭阳" })
    @PostMapping(value = "password/reset",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> resetPassword(@Validated @RequestBody SalesManResetPasswordDto salesManResetPasswordDto) {
		String phone = salesManResetPasswordDto.getPhone();
		String password = salesManResetPasswordDto.getPassword();
		int editResetPassword = salesManService.editResetPassword(phone,password);
		if(editResetPassword < 1){
			return new SalesManExcution<Void>(null, SalesManEnum.EDIT_PASSWORD_ERROR);
		}
		return new SalesManExcution<Void>(null, SalesManEnum.EDIT_PASSWORD_SUCCESS);
	}
	
	@ApiOperation(value = "业务员修改密码", nickname = "salesManChangePassword", notes = "", tags={ "@郭阳" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PostMapping(value = "password/change",
    	produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> changePassword(@Validated @RequestBody SalesManChangePasswordDto salesManChangePasswordDto) {
		String did = getDId();
		String userId = getUserId();
		String phone = getPhone();
		String oldPassword = salesManChangePasswordDto.getOldPassword();
		/*根据手机号查询密码*/
		String findPasswordByPhone = salesManService.findPasswordByPhone(did, userId, phone);
		if(!findPasswordByPhone.equals(oldPassword)){
			return new SalesManExcution<Void>(null, SalesManEnum.PASSWORD_ERROR);
		}
		String newpassword = salesManChangePasswordDto.getNewPassword();
   		int editPasswordByPhone = salesManService.editPasswordByPhone(did, userId, phone, newpassword);
   		if(editPasswordByPhone < 0){
			return new SalesManExcution<Void>(null, SalesManEnum.EDIT_PASSWORD_ERROR);
		}
		return new SalesManExcution<Void>(null, SalesManEnum.EDIT_PASSWORD_SUCCESS);
	}
	
	@ApiOperation(value = "业务员修改姓名", nickname = "salesManEditName", notes = "", tags={ "@郭阳" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PostMapping(value = "edit",
    	produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> edit(@Validated @RequestBody SalesManEditDto salesManEditDto) {
		String did = getDId();
		String userId = getUserId();
		int editSalesmanEditInfor = salesManService.editSalesmanEditInfor(did,salesManEditDto,userId);
		if(editSalesmanEditInfor < 1){
			return new SalesManExcution<Void>(null, SalesManEnum.EDIT_NAME_ERROR);
		}
		return new SalesManExcution<Void>(null, SalesManEnum.EDIT_NAME_SUCCESS);
	}
	
	@ApiOperation(value = "我的信息", nickname = "salesManInfo", notes = "", tags={ "@郭阳" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "info",
    	produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<SalesManInfo> info() {
		String userId = getUserId();
		String phone = getPhone();
		String did = getDId();
		UserIdAndName findDUserId = salesManService.findDUserId(userId,did,phone);
		String name = findDUserId.getName();
		String findTargetById = salesManService.findTargetById(userId,did);

		int target = Integer.valueOf(findTargetById);
		SalesManInfo salesManInfo = new SalesManInfo();
		salesManInfo.setTarget(target);
		salesManInfo.setUsername(name);
		String findCompleted = salesManService.findCompleted(userId,did);
		int completed = Integer.valueOf(findCompleted);
		salesManInfo.setCompleted(completed);
		return new SalesManExcution<SalesManInfo>(salesManInfo, SalesManEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "个人资料", nickname = "salesManData", notes = "", tags={ "@郭阳" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@GetMapping(value = "salesManData",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<SalesManData> salesManData() {
		String userId = getUserId();
		String did = getDId();
		SalesManData findSalesManData = salesManService.findSalesManData(did, userId);
		return new SalesManExcution<SalesManData>(findSalesManData, SalesManEnum.FIND_SUCCESS);
	}
}
